<template>
	<view class="register">
		<view class="register-header">
			<view class="header-1"></view>
			<view class="header-2">
				<image src="/static/logo.png"></image>
				教育培训系统
			</view>
			<view class="header-3"></view>
		</view>
		<view class="register-contanier">
			<view class="register-title">
				用户注册
			</view>
			<u--form labelPosition="left" :model="registForm" :rules="rules" ref="uForm" labelWidth="100">
				<view class="register-basic">
					<u-form-item label="姓名" required prop="userInfo.realName" borderBottom>
						<u--input placeholder="请输入姓名" v-model="registForm.userInfo.realName" border="none"></u--input>
					</u-form-item>

					<u-form-item label="联系电话" required prop="userInfo.mobilePhone" borderBottom>
						<u--input placeholder="请输入联系电话" v-model="registForm.userInfo.mobilePhone" border="none"
							maxlength="11"></u--input>
					</u-form-item>

					<u-form-item label="性别" required prop="userInfo.genderName" borderBottom @click="showSex = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.genderName" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择性别" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<u-form-item label="年龄" required prop="userInfo.age" borderBottom>
						<u--input placeholder="请输入年龄" v-model="registForm.userInfo.age" border="none"
							maxlength="3"></u--input>
					</u-form-item>

					<u-form-item label="邮箱" prop="userInfo.email" borderBottom>
						<u--input placeholder="请输入邮箱" v-model="registForm.userInfo.email" border="none"></u--input>
					</u-form-item>
				</view>

				<view class="register-info">
					<u-form-item label="职业" prop="userInfo.zhiye" borderBottom>
						<u--input placeholder="请输入职业" v-model="registForm.userInfo.zhiye" border="none"></u--input>
					</u-form-item>

					<u-form-item label="角色" required prop="userInfo.roleName" borderBottom @click="showRole = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.roleName" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择角色" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<u-form-item label="专业名称" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.zhuanye " borderBottom>
						<u--input placeholder="请输入专业名称" v-model="registForm.userInfo.zhuanye" border="none"></u--input>
					</u-form-item>

					<u-form-item label="职称" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.zhicheng " borderBottom>
						<u--input placeholder="请输入职称" v-model="registForm.userInfo.zhicheng" border="none"></u--input>
					</u-form-item>

					<u-form-item label="参加工作时间" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.entryDateVal" borderBottom @click="showTime = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.entryDateVal" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择参加工作时间" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</view>

				<view class="register-last">
					<u-form-item label="市县名称" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.authorizeAddressName" borderBottom @click="showSS = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.authorizeAddressName" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择市县名称" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<u-form-item label="单位性质" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.unitNatureName" borderBottom @click="showXZ = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.unitNatureName" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择单位性质" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<u-form-item label="单位级别" :required="registForm.userInfo.roleId == '668834371960045637'" prop="userInfo.unitLevelName" borderBottom @click="showJB = true;" style="pointer-events: auto;">
						<u--input v-model="registForm.userInfo.unitLevelName" disabled disabledColor="#ffffff" style="pointer-events: none;"
							placeholder="请选择单位级别" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</view>
				<view style="padding: 8px 8px 80px; background-color: #f9ecd9; color: #f1a532;">
					<view class="flex">
						<u-icon name="question-circle" color="#f1a532"></u-icon>
						<view style="padding-left: 6px;">温馨提示：</view>
					</view>
					<view style="padding-left: 16px;">1、请如实填写个人信息，您的个人信息受到严格保密；</view>
					<view style="padding-left: 16px;">2、参加血吸虫病科普的用户角色请选择“大众用户”，其余选“培训考试用户”；</view>
					<view style="padding-left: 16px;">3、一旦发现谎填用户信息，禁用该系统；</view>
				</view>
			</u--form>
		</view>
		<view class="register-btn">
			<view class="register-btn1">
				<u-button plain color="#2265EE" shape="circle" text="游客登录" @click="openTS(1)"></u-button>
			</view>
			<view class="register-btn2">
				<u-button color="#2265EE" shape="circle" text="注册" @click="openTS(2)"></u-button>
			</view>
		</view>
		<!--选择性别-->
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>
		<!--选择角色-->
		<u-picker :show="showRole" ref="rolePicker" :columns="actionsRole" keyName="fullName"
			@cancel="showRole = false;" @confirm="roleSelect"></u-picker>
		<!-- @change="changeHandler" -->
		<!-- <choose-role :show-choose.sync="showRole" @confirm="roleSelect"></choose-role> -->
		<!--选择市县-->
		<!-- <u-picker :show="showSS" :columns="actions2" @cancel="showSS = false;" @confirm="confirmCol"></u-picker> -->
		<choose-address :show-choose.sync="showSS" @cancel="showSS = false;" @confirm="confirmAddress"></choose-address>
		<!--选择单位性质-->
		<u-picker :show="showXZ" :columns="actionsNature" @cancel="showXZ = false;" keyName="fullName"
			@confirm="confirmNature"></u-picker>
		<!--选择单位级别-->
		
		<u-picker :show="showJB" :columns="actionsLevel" @cancel="showJB = false;" keyName="fullName"
			@confirm="confirmLevel"></u-picker>
		<!--选择入职时间-->
		<u-datetime-picker :show="showTime" v-model="registForm.userInfo.entryDate" mode="date"
			:minDate="entryMinDate" @cancel="showTime = false;" @confirm="confirmTime"></u-datetime-picker>
		<!---->
		<u-modal :show="showTS" :title="title" :content='content' :showCancelButton='showCancelButton'
			customStyle="32rpx 32rpx 32rpx 32rpx" :confirm-text="confirmText" align="center" @cancel="cancelModel"
			@confirm="confirmModel"></u-modal>
	</view>
</template>

<script>
	// import ChooseRole from '@/components/ChooseRole/index.vue'
	import ChooseAddress from '@/components/ChooseAddress/index.vue'
	import {
		getRoleByOrganize
	} from '@/api/role.js';
	import {
		getDictionary
	} from '@/api/dictionary.js';
	import {
		register, getConfigByKeyName
	} from '@/api/login.js'
	import moment from 'moment';
	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	const date = d.getDate()

	export default {
		name: 'register',
		components: {
			// ChooseRole,
			ChooseAddress
		},
		data() {
			return {
				passwordDef: '',
				showCancelButton: false,
				content: '',
				title: '提醒',
				showTS: false,
				entryMinDate: (new Date('1950-01-01')).getTime(),
				minDate: `${year-8}-${month}-${date}`, // 设置一个合法的默认最小日期
				maxDate: `${year}-${month}-${date}`, // 修正最大日期
				confirmText: "",
				showSex: false,
				showSS: false,
				showXZ: false,
				showJB: false,
				showRole: false,
				showTime: false,
				mode: 'range',
				registForm: {
					userInfo: {
						realName: '',
						mobilePhone: '',
						gender: '',
						genderName: '',
						email: '',
						zhiye: '',
						roleId: '',
						roleName: '',
						zhuanye: '',
						zhicheng: '',
						entryDate: '',
						entryDateVal: '',
						areaId: '',
						authorizeAddress: '',
						authorizeAddressName: '',
						unitNature: '',
						unitNatureName: '',
						unitLevel: '',
						unitLevelName: '',
						account: '',
						organizeId: '1',
						enabledMark: '1',
						sortCode: 0
					}
				},
				actions: [{
						name: '男',
						value: '1'
					},
					{
						name: '女',
						value: '2'
					}
				],
				actionsRole: [],
				roleData: [],
				actions2: [
					['中国', '美国', '日本']
				],
				actionsNature: [],
				actionsLevel: [],
				realRules: [],
				rules: {
					'userInfo.realName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.mobilePhone': {
						type: 'string',
						required: true,
						message: '请输入联系电话',
						trigger: ['blur', 'change']
					},
					'userInfo.age': {
						type: 'string',
						required: true,
						message: '请输入年龄',
						trigger: ['blur', 'change']
					},
					'userInfo.genderName': {
						type: 'string',
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
					'userInfo.roleName': {
						type: 'string',
						required: true,
						message: '请选择角色',
						trigger: ['blur', 'change']
					},
				},
				allRules: {
					'userInfo.realName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.mobilePhone': {
						type: 'string',
						required: true,
						message: '请输入联系电话',
						trigger: ['blur', 'change']
					},
					'userInfo.age': {
						type: 'string',
						required: true,
						message: '请输入年龄',
						trigger: ['blur', 'change']
					},
					'userInfo.genderName': {
						type: 'string',
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
					'userInfo.roleName': {
						type: 'string',
						required: true,
						message: '请选择角色',
						trigger: ['blur', 'change']
					},
					'userInfo.zhuanye': {
						type: 'string',
						required: true,
						message: '请选择专业',
						trigger: ['blur', 'change']
					},
					'userInfo.zhieye': {
						type: 'string',
						required: true,
						message: '请选择职业',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onLoad() {
			this.loadRole();
			this.loadDictNature();
			this.loadDictGrade();
			// // 加载角色
			// getRoleByOrganize().then(res => {
			// 	const roles = res.data.list.filter(
			// 		(o) => o.children && Array.isArray(o.children) && o.children.length
			// 	)
			// 	this.actionsRole = [roles[0].children.filter(item => (item.fullName != '管理员' && item.fullName != '游客'))];
			// })
			// // 加载单位性质
			// getDictionary('EnterpriseNature').then(res => {
			// 	this.actionsNature = [res.data.list];
			// })
			// // 加载单位级别
			// getDictionary('EnterpriseGrade').then(res => {
			// 	this.actionsLevel = [res.data.list];
			// })
		},
		methods: {
			// loadPwd() {
			// 	// 默认密码data传：defaultPassword
			// 	let data = 'defaultPassword'
			// 	getConfigByKeyName(data).then(res => {
			// 		this.passwordDef = res.data;
			// 	});
			// },
			// 加载角色
			loadRole() {
				let list = [
					{
						"id": "0",
						"hasChildren": true,
						"children": [
							{
								"id": "365139403107997317",
								"fullName": "管理员",
								"enCode": "Leader",
								"description": "",
								"enabledMark": 1,
								"creatorTime": 1669192419000,
								"sortCode": 0
							},
							{
								"id": "393332333610065861",
								"fullName": "游客",
								"enCode": "SimpleUser",
								"type": "",
								"description": "",
								"enabledMark": 1,
								"creatorTime": 1675914138000,
								"sortCode": 0
							},
							{
								"id": "668834371960045637",
								"fullName": "培训考试用户",
								"enCode": "0004",
								"type": "ApplicationRole",
								"description": "",
								"enabledMark": 1,
								"creatorTime": 1741598943000,
								"sortCode": 0
							},
							{
								"id": "669460031602688197",
								"fullName": "大众用户",
								"enCode": "04",
								"type": "ApplicationRole",
								"description": "",
								"enabledMark": 1,
								"creatorTime": 1741748112000,
								"sortCode": 0
							}
						],
						"fullName": "全局"
					}
				]
				const roles = list.filter(
					(o) => o.children && Array.isArray(o.children) && o.children.length
				)
				this.actionsRole = [roles[0].children.filter(item => (item.fullName != '管理员' && item.fullName != '游客'))];
			},
			// 加载单位性质
			loadDictNature() {
				this.actionsNature = [[
					{
						"id": "074a2706adc84abe8832b0b6a9f20229",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "其他",
						"enCode": "1"
					},
					{
						"id": "f4a0897d4f2d4e748a8f55ec7d85a82a",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "企业",
						"enCode": "2"
					},
					{
						"id": "82d9060f011a42dd8488a9feaaef376e",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "海关",
						"enCode": "3"
					},
					{
						"id": "cf5b616c15ed40c3bfbf59d4f6e8b7fb",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "医疗机构",
						"enCode": "4"
					},
					{
						"id": "2a3fa24dcace4a7aafeddb3d8c0ec65a",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "疾控",
						"enCode": "5"
					}
				]]
			},
			// 加载单位级别
			loadDictGrade() {
				this.actionsLevel = [[
					{
						"id": "664532605936336965",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "省级",
						"enCode": "1"
					},
					{
						"id": "664532694918496325",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "市级",
						"enCode": "2"
					},
					{
						"id": "664532758957129797",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "县区",
						"enCode": "3"
					},
					{
						"id": "664532836245569605",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "乡镇",
						"enCode": "4"
					},
					{
						"id": "664532928696418373",
						"parentId": "0",
						"hasChildren": false,
						"children": null,
						"fullName": "社区",
						"enCode": "5"
					}
				]]
			},
			disabledDate(date) {
				return false; // 不限制任何日期
			},
			/**
			 * 确认选择性别
			 * @param {Object} e
			 */
			sexSelect(e) {
				this.registForm.userInfo.genderName = e.name
				this.registForm.userInfo.gender = e.value
				this.$refs.uForm.validateField('userInfo.sex')
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.rolePicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.roleData[index])
				}
			},
			roleSelect(e) {
				this.showRole = false;
				this.registForm.userInfo.roleId = e.value[0].id
				this.registForm.userInfo.roleName = e.value[0].fullName
				this.$refs.uForm.validateField('userInfo.role')
			},
			// roleSelect(roles) {
			// 	this.showRole = false;
			// 	this.registForm.userInfo.roleId = roles.map(item => {
			// 		return item.id;
			// 	});
			// 	this.registForm.userInfo.roleName = roles.map(item => {
			// 		return item.fullName;
			// 	}).join(',');
			// 	this.$refs.uForm.validateField('userInfo.role')
			// },
			// 选省市县回调
			confirmAddress(e) {
				this.showSS = false
				// 接受到参数
				const areaIds = e.map(item => {
					return item.id
				})
				this.registForm.userInfo.authorizeAddress = areaIds;
				this.registForm.userInfo.areaId = areaIds.join(',');
				this.registForm.userInfo.authorizeAddressName = e.map(item => {
					return item.fullName
				}).join('/');
			},
			// 选择性质回调
			confirmNature(e) {
				this.showXZ = false;
				this.registForm.userInfo.unitNatureName = e.value[0].fullName
				this.registForm.userInfo.unitNature = e.value[0].enCode
			},
			// 选择级别回调
			confirmLevel(e) {
				this.showJB = false
				this.registForm.userInfo.unitLevelName = e.value[0].fullName
				this.registForm.userInfo.unitLevel = e.value[0].enCode
			},
			// 选择入职时间回调
			confirmTime(e) {
				this.showTime = false
				// 格式化日期
				this.registForm.userInfo.entryDateVal = moment(e.value).format('YYYY-MM-DD');
			},
			openTS(val) {
				if (val === 1) {
					this.showTS = true
					this.showCancelButton = true
					this.content = '游客进入不会保留任何学习记录'
					this.confirmText = "已读"
					return;
				}
				// 表单校验
				this.$refs.uForm.validate().then(res => {
					if (this.registForm.userInfo.roleId == '668834371960045637') {
						// 校验数据
						if (!this.registForm.userInfo.zhuanye) {
							uni.showToast({
								title: '请输入专业名称',
								icon: 'none'
							})
							return;
						}
						if (!this.registForm.userInfo.zhicheng) {
							uni.showToast({
								title: '请输入职称',
								icon: 'none'
							})
							return;
						}
						if (!this.registForm.userInfo.entryDate) {
							uni.showToast({
								title: '请选择参加工作时间',
								icon: 'none'
							})
							return;
						}
						if (!this.registForm.userInfo.authorizeAddressName) {
							uni.showToast({
								title: '请选择市县名称',
								icon: 'none'
							})
							return;
						}
						if (!this.registForm.userInfo.unitNatureName) {
							uni.showToast({
								title: '请选择单位性质',
								icon: 'none'
							})
							return;
						}
						if (!this.registForm.userInfo.unitLevelName) {
							uni.showToast({
								title: '请选择单位级别',
								icon: 'none'
							})
							return;
						}
					}
					// 调用注册接口
					// 如果地区的authorizeAddress是空的,就不要传这个字段
					// if (!this.registForm.userInfo.authorizeAddress) {
					delete this.registForm.userInfo.authorizeAddress
					delete this.registForm.userInfo.authorizeAddressName
					// }
					// account 把这个字段同时赋值成手机号
					this.registForm.userInfo.account = this.registForm.userInfo.mobilePhone
					register(this.registForm.userInfo).then(res => {
						this.showTS = true
						this.showCancelButton = false
						this.content = '您的网页登录账号为手机号码。初始密码为：'+res.data.keyValue+'，忘记密码请至“我的”页面修改！'
						this.confirmText = "确认"
					});
				}).catch(errors => {
					console.log(errors);
				})

			},
			cancelModel() {
				this.showTS = false
			},
			confirmModel() {
				this.showTS = false
				if (this.showCancelButton) {
					uni.setStorageSync('isTourist', true);
					// 说明是游客登陆的
					let param = {
						account: 'tourist',
						password: 'admin@888'
					}
					this.$store.dispatch('user/login', param)
					.then(() => {
						uni.switchTab({
							url:'/pages/index/index'
						})
					})
					.catch((err) => { 	
						this.showSuccess(err,'none');
					})
				} else {
					uni.setStorageSync('isTourist', false);
					// 注册的用户，跳转到登录也
					uni.reLaunch({
						url: '/pages/register/login'
					});
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.register-header {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #fff;
		display: flex;

		.header-1 {
			flex: 1;
		}

		.header-2 {
			flex: 10;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;

			image {
				width: 48rpx;
				height: 48rpx;
				margin-right: 16rpx;
			}
		}

		.header-3 {
			flex: 1;
		}
	}

	.register {
		background-color: #F6F8FC;
		width: 100%;
		height: 100vh;
		overflow: hidden;
		position: relative;

		.register-contanier {
			width: 100%;
			height: calc(100vh - 88rpx);
			overflow: auto;
			overflow-x: hidden;

			.register-title {
				box-sizing: border-box;
				padding: 32rpx 32rpx 16rpx 32rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #323233;
				line-height: 40rpx;
				text-align: left;
				font-style: normal;
			}

			.register-basic {
				width: 100%;
				min-height: 440rpx;
				background-color: #fff;
				box-sizing: border-box;
				padding: 0 32rpx;
			}

			.register-info {
				margin-top: 32rpx;
				width: 100%;
				min-height: 440rpx;
				background-color: #fff;
				box-sizing: border-box;
				padding: 0 32rpx;
			}

			.register-last {
				margin-top: 32rpx;
				margin-bottom: 12rpx;
				width: 100%;
				background-color: #fff;
				box-sizing: border-box;
				padding: 0 32rpx;
			}
		}

		.register-btn {
			width: 100%;
			height: 112rpx;
			position: absolute;
			background-color: #fff;
			bottom: 0;
			display: flex;
			box-sizing: border-box;
			padding: 10rpx 32rpx;

			.register-btn1 {
				flex: 1;
			}

			.register-btn2 {
				flex: 1;
				margin-left: 24rpx;
			}
		}
	}

	/deep/ .uni-input-input {
		text-align: right;
	}

	/deep/ .u-form-item__body__right__message {
		text-align: right;
	}

	/deep/ .uni-input-placeholder {
		text-align: right;
	}
</style>